import { GetChannel } from '@/utils/storage';

const initialState = {
  AllchannelList: [] as ChannelListType[],
  userChannelList: GetChannel(),
  channel_id: '0' as string,
};

export type ChannelListType = {
  id: number;
  name: string;
};

export type ChannelActionType =
  | {
      type: 'channel/SaveAllChannel';
      payload: ChannelListType[];
    }
  | {
      type: 'channel/SaveuserChannel';
      payload: ChannelListType[];
    }
  | {
      type: 'channel/UpdateAddChannel';
      payload: ChannelListType;
    }
  | {
      type: 'channel/DelAddChannel';
      payload: number;
    }
  | {
      type: 'articles/SaveChannel_id';
      payload: string;
    };

export default function ChannelReducer(
  state = initialState,
  action: ChannelActionType
): typeof initialState {
  switch (action.type) {
    case 'channel/SaveAllChannel':
      return {
        ...state,
        AllchannelList: action.payload,
      };
    case 'channel/SaveuserChannel':
      return {
        ...state,
        userChannelList: action.payload,
      };
    case 'channel/UpdateAddChannel':
      return {
        ...state,
        userChannelList: [...state.userChannelList, action.payload],
      };
    case 'channel/DelAddChannel':
      return {
        ...state,
        userChannelList: state.userChannelList.filter((item) => {
          return item.id !== action.payload;
        }),
      };
    case 'articles/SaveChannel_id':
      return { ...state, channel_id: action.payload };

    default:
      return state;
  }
}
